package com.tg.paw.common.component;

import com.tg.paw.common.constant.CommonConstant;
import com.tg.paw.common.entity.User;
import com.tg.paw.common.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Rubble
 * @date 2020/6/13
 */
@Slf4j
@Component
public class UserUtil {


    /**
     * Spring并没有注入一个request对象，而是注入了一个代理（proxy）；当Bean中需要使用request对象时，通过该代理获取request对象。
     * 调用request的方法method时，实际上是调用了由objectFactory.getObject()生成的对象的method方法；objectFactory.getObject()生成的对象才是真正的request对象。
     *
     * objectFactory的类型为WebApplicationContextUtils的内部类RequestObjectFactory；
     * 而RequestObjectFactory要获得request对象需要先调用currentRequestAttributes()方法获得RequestAttributes对象，
     * 生成RequestAttributes对象的核心代码在类RequestContextHolder中，生成的RequestAttributes对象是线程局部变量（ThreadLocal），
     * 因此request对象也是线程局部变量；这就保证了request对象的线程安全性。
     * RequestContextHolder.currentRequestAttributes()
     *
     * 链接：https://www.jianshu.com/p/579ef18709cf
     */
    private static HttpServletRequest request;

    @Autowired
    public void setRequest(HttpServletRequest request) {
        UserUtil.request = request;
    }

    public static User getLoginUser(){
        String username = null;
        User user = null;
        try {
            username = request.getHeader(CommonConstant.USER_NAME);
            if(username!=null){
                String userIdStr = request.getHeader(CommonConstant.USER_ID);
                user = new User(Long.valueOf(userIdStr),username);
            }else {
                String token = request.getHeader(CommonConstant.ACCESS_TOKEN);
                if(token!=null){
                    if(token.contains(CommonConstant.BEARER_TOKEN)){
                        token = token.replace(CommonConstant.BEARER_TOKEN,"").trim();
                    }
                    user = JWTUtil.getUserInfo(token);
                }
            }
            if(user==null){
                user = new User(-1L,CommonConstant.GUEST_USER);
            }
        }catch (Exception e){
            log.error("获取header用户异常.",e);
        }
        return user;
    }


}
